#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/select.h>

#define PORT 8081
#define BUFFER_SIZE 1024
#define MAX_CLIENTS 10

std::map<std::string, std::string> translation_map = {
    {"Hello", "你好"},
    {"How are you?", "你好吗"},
    {"Goodbye", "再见"}};

int main()
{
    int master_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (master_socket < 0)
    {
        perror("Socket creation failed");
        return 1;
    }

    // 设置端口复用
    int opt = 1;
    setsockopt(master_socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

    struct sockaddr_in address;
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(PORT);

    if (bind(master_socket, (struct sockaddr *)&address, sizeof(address)) < 0)
    {
        perror("Bind failed");
        return 1;
    }

    if (listen(master_socket, MAX_CLIENTS) < 0)
    {
        perror("Listen failed");
        return 1;
    }

    std::cout << "Server listening on port " << PORT << std::endl;

    fd_set readfds;
    std::vector<int> client_sockets;
    int max_sd = master_socket;

    while (true)
    {
        FD_ZERO(&readfds);
        FD_SET(master_socket, &readfds);
        for (int sd : client_sockets)
        {
            FD_SET(sd, &readfds);
            if (sd > max_sd)
                max_sd = sd;
        }

        int activity = select(max_sd + 1, &readfds, NULL, NULL, NULL);
        if (activity < 0)
        {
            perror("Select error");
            break;
        }

        // 处理新连接
        if (FD_ISSET(master_socket, &readfds))
        {
            struct sockaddr_in client_addr;
            socklen_t addrlen = sizeof(client_addr);
            int new_socket = accept(master_socket, (struct sockaddr *)&client_addr, &addrlen);
            if (new_socket < 0)
            {
                perror("Accept failed");
                continue;
            }

            std::cout << "New connection: "
                      << inet_ntoa(client_addr.sin_addr) << ":"
                      << ntohs(client_addr.sin_port) << std::endl;

            client_sockets.push_back(new_socket);
            if (new_socket > max_sd)
                max_sd = new_socket;
        }

        // 处理客户端请求
        for (size_t i = 0; i < client_sockets.size(); ++i)
        {
            int sd = client_sockets[i];
            if (FD_ISSET(sd, &readfds))
            {
                char buffer[BUFFER_SIZE] = {0};
                int valread = read(sd, buffer, BUFFER_SIZE);
                if (valread <= 0)
                {
                    // 客户端断开连接
                    sockaddr_in address;
                    socklen_t addrlen = sizeof(address);
                    getpeername(sd, (struct sockaddr *)&address, &addrlen);
                    std::cout << "Client disconnected: "
                              << inet_ntoa(address.sin_addr) << ":"
                              << ntohs(address.sin_port) << std::endl;
                    close(sd);
                    client_sockets.erase(client_sockets.begin() + i);
                    --i; // 防止跳过下一个客户端
                }
                else
                {
                    std::string request(buffer, valread); // 精确构造请求字符串
                    std::string response;

                    auto it = translation_map.find(request);
                    if (it != translation_map.end())
                    {
                        response = it->second;
                    }
                    else
                    {
                        response = "[Error] Translation not found";
                    }

                    send(sd, response.c_str(), response.size(), 0);
                    std::cout << "Request: " << request
                              << " -> Response: " << response << std::endl;
                }
            }
        }
    }

    close(master_socket);
    return 0;
}